<?php

namespace app\modules\controllers;
use app\modules\models\Brand;
use app\modules\models\Product;
use Yii;
use yii\data\Pagination;

class BrandController extends CommonController
{ 
    protected $mustlogin = ['list', 'add', 'mod', 'del'];

    public function actionList()
    {
        $this->layout = "layout1";
        $model = Brand::find()->orderBy('brandid DESC');
        $count = $model->count();
        $pageSize = Yii::$app->params['pageSize']['manage'];
        $pager = new Pagination(['totalCount' => $count, 'pageSize' => $pageSize]);
        $data = $model->offset($pager->offset)->limit($pager->limit)->all();
        return $this->render("brands", ['data' => $data, 'pager' => $pager]);
    }

    public function actionAdd()
    {
        $model = new Brand();
        $this->layout = "layout1";
        if (Yii::$app->request->isPost) {
            $post = Yii::$app->request->post();
            if ($model->add($post)) {
                //Yii::$app->session->setFlash("info", "添加成功");
                $this->redirect(['brand/list']);
            }
        }
        return $this->render("add", ['model' => $model,'title'=>'添加品牌']);
    }

    public function actionMod()
    {
        $this->layout = "layout1";
        $brandid = Yii::$app->request->get("brandid");
        $model = Brand::find()->where('brandid = :id', [':id' => $brandid])->one();
        if (Yii::$app->request->isPost) {
            $post = Yii::$app->request->post();
            if ($model->load($post) && $model->save()) {
                //Yii::$app->session->setFlash('info', '修改成功');
                $this->redirect(['brand/list']);
            }
        }
        return $this->render('add', ['model' => $model,'title'=>'修改品牌']);
    }

    public function actionDel()
    {
        try {
            $brandid = Yii::$app->request->get('brandid');
            if (empty($brandid)) {
                throw new \Exception('参数错误');
            }
            $data = Product::find()->where('brandid = :bid', [":bid" => $brandid])->one();
            if ($data) {
                throw new \Exception('该品牌下面有关联产品，不允许删除');
            }
            if (!Brand::deleteAll('brandid = :id', [":id" => $brandid])) {
                throw new \Exception('删除失败');
            }
            Yii::$app->session->setFlash('info', '删除成功');
        } catch(\Exception $e) {
            Yii::$app->session->setFlash('info', $e->getMessage());
        }
        return $this->redirect(Yii::$app->request->referrer);
    }





}